import { Singleton } from "db://assets/Scripts/Base/Singleton";

interface IEventData {
  func: Function;
  target: any;
}

interface IEvent {
  [eventName: string]: IEventData[];
}

export class CustomEventListener extends Singleton {
  handle: IEvent = {};

  on(eventName: string, callBack: Function, target?: any) {
    if (!this.handle[eventName]) {
      this.handle[eventName] = [];
    }

    // 设置为非一次性监听器
    const data: IEventData = { func: callBack, target };
    this.handle[eventName].push(data);
  }

  off(eventName: string, callBack: Function, target?: any) {
    const list = this.handle[eventName];
    if (!list || list.length <= 0) {
      return;
    }

    for (let index = 0; index < list.length; index++) {
      const element = list[index];
      if (element.func === callBack && (!target || target === element.target)) {
        list.splice(index, 1);
        break;
      }
    }
  }

  dispatchEvent(eventName: string, ...args: any) {
    const list = this.handle[eventName];
    if (!list || list.length <= 0) {
      return;
    }

    for (let index = 0; index < list.length; index++) {
      const element = list[index];
      element.func.apply(element.target, args);
    }
  }

  // 重写getInstance方法,确保返回类型为 CustomEventListener
  static getInstance(): CustomEventListener {
    if (!this.instance) {
      this.instance = new this();
    }
    return this.instance as CustomEventListener;
  }
}
